<template>
  <div class="app-container">
    <div class="data-tree">
      <el-button
        size="small"
        type="info"
        icon="el-icon-sort"
        @click="toggleExpandAll"
      >
        展开/折叠
      </el-button>
      <el-divider />
      <el-tree
        ref="dataTree"
        node-key="id"
        highlight-current
        accordion
        :indent="0"
        :expand-on-click-node="false"
        :default-expand-all="expanded"
        :props="treeProps"
        :data="tableTreeData"
        @node-click="handleTreeNodeClick"
      >
        <span slot-scope="{ node, data }" class="custom-tree-node">
          <i class="folder"></i>
          <span
            class="label"
            :title="data.idx ? `${data.idx} ${node.label}` : node.label"
          >
            {{ data.idx ? `${data.idx} ${node.label}` : node.label }}
          </span>
        </span>
      </el-tree>
    </div>

    <div class="data-main">
      <el-row class="mb15">
        <el-button type="primary" @click="addFolder">创建文件夹</el-button>
        <el-button
          v-if="folderId"
          type="primary"
          icon="el-icon-download"
          :disabled="selectionIds.length == 0"
          @click="downloadFile"
        >
          批量下载
        </el-button>
        <el-button v-if="folderId" type="warning" @click="upload.open = true">
          上传
        </el-button>
        <!-- <el-form class="fr" inline :model="formInline">
          <el-form-item label="文件名称">
            <el-input
              v-model="formInline.name"
              clearable
              placeholder="请输入文件名称"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search">查询</el-button>
          </el-form-item>
        </el-form> -->
      </el-row>

      <el-table
        v-loading="listLoading"
        :data="tableData"
        style="width: 100%"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          v-if="folderId"
          type="selection"
          align="center"
          width="55"
        />
        <el-table-column label="名称">
          <template slot-scope="{ row }">
            <!-- 判断是文件夹还是文件 -->
            <el-link
              v-if="row.type == 1"
              :underline="false"
              @click="jumpFolder(row.id)"
            >
              <img
                src="@/assets/static/folder.png"
                style="vertical-align: text-top"
              />
              {{ row.name }}
            </el-link>
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="大小" align="center" width="120">
          <template slot-scope="{ row }">
            {{
              row.type == 1
                ? "-"
                : Math.round(row.size / 1024) < 1024
                ? Math.round(row.size / 1024) + "KB"
                : Math.round(row.size / 1024 / 1024) + "M"
            }}
          </template>
        </el-table-column>
        <el-table-column label="成果名称" align="center" width="120">
          <template slot-scope="{ row }">
            {{ row.title || "-" }}
          </template>
        </el-table-column>
        <el-table-column
          label="创建者"
          align="center"
          prop="createBy"
          width="120"
        />
        <el-table-column
          label="更新时间"
          align="center"
          prop="updateTime"
          width="200"
        />
        <el-table-column
          label="操作"
          align="center"
          :width="!folderId ? 250 : 290"
        >
          <template slot-scope="{ row }">
            <el-button
              v-if="!folderId"
              size="mini"
              type="warning"
              plain
              @click="quickPrint(row)"
            >
              快捷打印
            </el-button>
            <el-button
              v-if="folderId"
              size="mini"
              type="warning"
              plain
              @click="singlePrint(row)"
            >
              打印
            </el-button>
            <el-button
              v-if="folderId"
              size="mini"
              type="success"
              plain
              @click="move(row)"
            >
              移动
            </el-button>
            <el-button size="mini" type="primary" plain @click="download(row)">
              下载
            </el-button>
            <el-button size="mini" type="danger" plain @click="del(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="total > 0"
        style="margin-top: 10px"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        :current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        @size-change="onPageSizeChange"
        @current-change="onCurrentPageChange"
      />
    </div>

    <el-dialog
      class="move-dialog"
      width="550px"
      title="移动到"
      :visible.sync="dialog.visible"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-tree
        ref="folderTree"
        node-key="id"
        highlight-current
        default-expand-all
        :props="treeProps"
        :data="treeData"
        @node-click="handleNodeClick"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button
          type="primary"
          :disabled="!dialog.toMoveId"
          @click="confirmDialog"
        >
          移动到此
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      width="550px"
      title="快捷打印"
      :visible.sync="printDialog.visible"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-tree
        ref="printTree"
        node-key="id"
        highlight-current
        default-expand-all
        :expand-on-click-node="false"
        show-checkbox
        :props="treeProps"
        :data="treeData"
        @check="handleCheckChange"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="printDialog.visible = false">取 消</el-button>
        <el-button
          type="primary"
          :disabled="printDialog.checkedKeys.length === 0"
          @click="printClick"
        >
          打 印
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      width="400px"
      title="上传"
      :visible.sync="upload.open"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="成果名称" prop="title">
          <el-input
            v-model="form.title"
            clearable
            placeholder="请输入成果名称"
          />
        </el-form-item>
        <el-form-item label="完成人员" prop="userIds">
          <el-select
            style="width: 100%"
            v-model="form.userIds"
            filterable
            multiple
            clearable
            placeholder="请选择完成人员"
          >
            <el-option
              v-for="item in peopleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择文件" prop="file">
          <el-upload
            ref="upload"
            :headers="upload.headers"
            :action="upload.action"
            :data="upload.params"
            :auto-upload="false"
            :limit="1"
            :before-upload="beforeUpload"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
          >
            <el-button slot="trigger" type="primary">上 传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="closeUploadDialog">取 消</el-button>
          <el-button type="primary" @click="handleUpload">提 交</el-button>
        </el-form-item>
      </el-form>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="confirmDialog"> 上 传 </el-button>
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import printJS from "print-js";
import {
  getTreeNode,
  getChildrenNode,
  getChildrenTreeNode,
  // getDocumentByName,
  uploadOrBuildDocument,
  downFileOrFolder,
  updateDocument,
  deleteDocument,
  printDocument,
  batchDownLoad,
} from "@/api2/projectManagement/process";
import { apiPeoList } from "@/api2/projectManagement/reporting";
import { getToken } from "@/utils/auth";
const base_url = process.env.VUE_APP_BASE_APITwo;

export default {
  data() {
    const validator = (rule, value, callback) => {
      if (this.fileList.length === 0) {
        callback(new Error("文件不能为空"));
      } else {
        callback();
      }
    };
    return {
      expanded: true,
      tableTreeData: [],
      upload: {
        headers: { Authorization: getToken(), platform: 'WEB' },
        action: base_url + "/xm/project/document/uploadFile",
        open: false,
        params: {},
      },
      form: { userIds: [] },
      rules: {
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        file: [{ validator, trigger: "change" }],
      },
      fileList: [],
      peopleList: [],
      // formInline: {},
      listLoading: false,
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      selectionIds: [],
      folderId: 0,
      treeData: [],
      treeProps: { label: "name" },
      dialog: {
        visible: false,
        movedId: undefined,
        movedPid: undefined,
        toMoveId: undefined,
      },
      printDialog: {
        visible: false,
        checkedKeys: [],
      },
    };
  },
  async mounted() {
    this.getPeoPleList();
    await this.getNode();
    this.$nextTick(() => {
      this.$refs.dataTree.setCurrentKey(0);
    });
  },
  methods: {
    toggleExpandAll() {
      const treeNode = this.$refs.dataTree.store.nodesMap;
      for (let key in treeNode) {
        treeNode[key].expanded = !this.expanded;
      }
      this.expanded = !this.expanded;
    },
    // 获取负责人
    async getPeoPleList() {
      const res = await apiPeoList();
      this.peopleList = res.data;
    },
    async getNode() {
      this.listLoading = true;
      const data = await getTreeNode();
      this.listLoading = false;
      this.tableData = data.data;
      this.tableTreeData = [
        {
          id: 0,
          name: "资料管理",
          children: this.renderTreeNode(data.data),
        },
      ];
    },
    renderTreeNode(data, index) {
      return data.map((v, i) => {
        const idx = index ? index + "." + (i + 1) : i + 1;
        this.$set(v, "idx", idx);
        if (v.children?.length) {
          v.children = this.renderTreeNode(v.children, v.idx);
        }
        return v;
      });
    },
    handleTreeNodeClick({ id }) {
      if (this.folderId === id) return;
      this.jumpFolder(id);
    },
    getList() {
      this.listLoading = true;
      const params = {
        id: this.folderId,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      getChildrenNode(params).then((data) => {
        this.listLoading = false;
        this.tableData = data.data;
        this.total = data.total || 0;

        this.$nextTick(() => {
          this.$refs.dataTree.setCurrentKey(this.folderId || 0);
        });
      });
    },
    onPageSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.getList();
    },
    onCurrentPageChange(val) {
      this.pageNum = val;
      this.getList();
    },
    handleSelectionChange(val) {
      this.selectionIds = val.map((item) => {
        const { id, pid, type } = item;
        return { id, pid, type };
      });
    },
    // async search() {
    //   if (this.formInline.name) {
    //     this.listLoading = true;
    //     const res = await getDocumentByName({
    //       name: this.formInline.name,
    //       pageNum: this.pageNum,
    //       pageSize: this.pageSize,
    //     });
    //     this.listLoading = false;
    //     this.tableData = res.data;
    //     this.total = res.total;
    //   } else {
    //     this.folderId = undefined;
    //     this.getList();
    //   }
    // },
    jumpFolder(id) {
      this.folderId = id;
      this.pageNum = 1;
      this.getList();
    },
    addFolder() {
      this.$prompt(`请输入新文件夹名称`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputValidator: (value) => {
          if (!value) {
            return "名称不能为空！";
          }
          if (value.length > 10) {
            return "名称限制10个字以内！";
          }
        },
      })
        .then(async ({ value }) => {
          const params = {
            name: value,
            type: 1,
            pid: this.folderId || "0",
          };
          await uploadOrBuildDocument(params);
          this.$message.success("新增成功");
          Promise.all([this.getNode(), this.getList()]);
        })
        .catch(() => {});
    },
    async downloadFile() {
      const res = await batchDownLoad(this.selectionIds);
      let a = document.createElement("a");
      a.href = res.data.url;
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    },
    closeUploadDialog() {
      this.fileList = [];
      this.$refs.upload.clearFiles();
      this.$refs.form.resetFields();
      this.upload.open = false;
    },
    handleChange(file, fileList) {
      this.fileList = [file];
      this.$refs.form.validateField("file");
    },
    handleRemove(file, fileList) {
      this.fileList = [];
      this.$refs.upload.clearFiles();
      this.$refs.form.validateField("file");
    },
    beforeUpload(rawFile) {
      const isLt10M = rawFile.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("文件大小限制在 10MB 内!");
        return false;
      }
    },
    handleUpload() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let { title, userIds } = this.form;
          userIds = userIds.join();
          this.$set(this.upload.params, "title", title);
          this.$set(this.upload.params, "userIds", userIds);
          this.$refs.upload.submit();
        }
      });
    },
    async handleSuccess(res) {
      if (res.code === 0) {
        const { fileName, url, size, title, userIds } = res.data;
        const params = {
          name: fileName,
          fileUrl: url,
          size,
          type: 2,
          pid: this.folderId,
          title,
          userIds,
        };
        await uploadOrBuildDocument(params);
        this.$message.success("文件上传成功");
        this.closeUploadDialog();
        this.getList();
      } else if (res.code != 0 && res.msg) {
        this.$message.error(res.msg);
      } else {
        this.$message.error("上传失败，请重试！");
      }
    },
    quickPrint({ id }) {
      this.printDialog.visible = true;
      this.printDialog.checkedKeys = [];
      getChildrenTreeNode({ id }).then((data) => {
        this.treeData = data.data;
      });
    },
    handleCheckChange(data, checked) {
      this.printDialog.checkedKeys = checked.checkedKeys;
    },
    singlePrint({ id }) {
      this.printDialog.checkedKeys = [id];
      this.printClick();
    },
    async printClick() {
      const res = await printDocument(this.printDialog.checkedKeys.join());
      printJS(res.data.url);
    },
    move(row) {
      this.dialog.visible = true;
      this.dialog.movedId = row.id;
      this.dialog.movedPid = row.pid;
      const id = row.topId;
      getChildrenTreeNode({ id }).then((data) => {
        this.treeData = data.data;
      });
    },
    async handleNodeClick(data) {
      // 只能选文件夹、不能选最外层文件夹、不能选自己的父级、不能选自己
      if (
        data.type == 1 &&
        data.pid != 0 &&
        this.dialog.movedPid != data.id &&
        this.dialog.movedId != data.id
      ) {
        this.$set(this.dialog, "toMoveId", data.id);
      } else {
        this.$refs.folderTree.setCurrentKey(this.dialog.toMoveId);
      }
    },
    closeDialog() {
      this.dialog.visible = false;
      this.dialog.movedId = undefined;
      this.dialog.movedPid = undefined;
      this.dialog.toMoveId = undefined;
    },
    async confirmDialog() {
      const { movedId: id, toMoveId: pid } = this.dialog;
      await updateDocument({ id, pid });
      this.$message.success("移动成功");
      if (this.tableData.length == 1) {
        this.folderId = this.dialog.toMoveId;
      }
      Promise.all([this.getNode(), this.getList()]);
      this.closeDialog();
    },
    async download({ id }) {
      const res = await downFileOrFolder(id);
      const a = document.createElement("a");
      a.style.display = "none";
      a.href = res.data.url;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    },
    del(row) {
      const typename = row.type == 1 ? "文件夹" : "文件";
      this.$confirm(`是否删除名为 ${row.name} 的${typename}?`, {
        type: "warning",
      })
        .then(async () => {
          await deleteDocument(row.id);
          this.$message.success("删除成功");
          if (row.type == 1) {
            Promise.all([this.getNode(), this.getList()]);
          } else {
            this.getList();
          }
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  height: 100%;
  display: flex;
  background-color: #f4f5fc;
  .data-tree,
  .data-main {
    padding: 12px 20px;
    border: 1px solid #dcdfe6;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
    background-color: #fff;
  }
  .data-tree {
    width: 350px;
    margin-right: 15px;
    overflow: auto;
    ::v-deep .el-tree {
      .el-tree-node {
        position: relative;
        padding-left: 16px; // 缩进量
      }
      > .el-tree-node {
        padding-left: 0; // 缩进量
      }
      .el-tree-node__children {
        padding-left: 16px; // 缩进量
      }
      // 竖线
      .el-tree-node::before {
        content: "";
        width: 1px;
        height: 100%;
        position: absolute;
        left: -4px;
        top: -15px;
        border-left: 1px dashed #52627c;
      }
      // 当前层最后一个节点的竖线高度固定
      .el-tree-node:last-child::before {
        height: 30px; // 可以自己调节到合适数值
      }
      // 横线
      .el-tree-node::after {
        content: "";
        width: 24px;
        height: 30px;
        position: absolute;
        left: -3px;
        top: 15px;
        border-top: 1px dashed #52627c;
      }

      // 去掉最顶层的虚线，放最下面样式才不会被上面的覆盖了
      & > .el-tree-node::after {
        border-top: none;
      }
      & > .el-tree-node::before {
        border-left: none;
      }

      // 展开关闭的icon
      .el-tree-node__expand-icon {
        // 叶子节点（无子节点）
        &.is-leaf {
          color: transparent;
          width: 0;
          // display: none; // 也可以去掉
        }
      }
    }
  }
  .data-main {
    flex: 1;
    overflow: auto;
  }
}
.el-divider--horizontal {
  margin: 12px 0 8px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 5px;
  overflow: hidden;
  .label {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .folder {
    width: 16px;
    height: 16px;
    margin-right: 8px;
    background: url("../../../assets/static/folder.png") no-repeat;
    background-size: 100% 100%;
  }
}
::v-deep {
  .el-tree-node__content {
    height: 30px;
  }
  .el-tree-node.is-current > .el-tree-node__content {
    color: #3b95ff;
  }
}

// .el-form-item {
//   &:last-child {
//     margin-right: 0;
//   }
// }
.mb15 {
  margin-bottom: 15px;
}
.dialog-footer {
  text-align: center;
}
</style>
